package com.liuxu.topnews.Manager;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.liuxu.topnews.AppInfo;
import com.liuxu.topnews.MyApplication;

import java.util.List;

import static android.content.ContentValues.TAG;

public class BackGroudManager {
    public void clean() {
        ActivityManager mActivityManager = (ActivityManager) MyApplication.getContext().getSystemService(Context.ACTIVITY_SERVICE);
        //返回在设备上运行的应用程序的进程的列表
        List<ActivityManager.RunningAppProcessInfo> appProcessInfos = mActivityManager.getRunningAppProcesses();
        //返回当前正在运行的服务的列表
//        List<ActivityManager.RunningServiceInfo> serviceInfos = mActivityManager.getRunningServices(100);
        long beforeMem = getAvailMemory(MyApplication.getContext());
        int count = 0;
        Log.v("获取到进程数",String.valueOf(appProcessInfos.size()));
        String[] appInfo=new AppInfo().apppacks;
        for (int i = 0; i < appInfo.length; ++i){
            mActivityManager.killBackgroundProcesses(appInfo[i]);
        }
        for (int i = 0; i < appProcessInfos.size(); ++i) {
            ActivityManager.RunningAppProcessInfo appProcessInfo = appProcessInfos.get(i);
            if (appProcessInfo.importance > ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                String[] pkgList = appProcessInfo.pkgList;
                for (int j = 0; j < pkgList.length; ++j) {//pkgList 得到该进程下运行的包名
                    Log.d(TAG, "It will be killed, package name : " + pkgList[j]);
                    mActivityManager.killBackgroundProcesses(pkgList[j]);
                    count++;
                }
            }
        }
        long afterMem = getAvailMemory(MyApplication.getContext());
        showtoast("清除" +count+"个进程，共"+ (afterMem - beforeMem) + "M内存");
    }

    private long getAvailMemory(Context context) {
        // 获取android当前可用内存大小
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        //mi.availMem; 当前系统的可用内存
        //return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化
        Log.d(TAG, "可用内存---->>>" + mi.availMem / (1024 * 1024));
        return mi.availMem / (1024 * 1024);
    }
    private void showtoast(final String text){
        Handler handlerThree=new Handler(
                Looper.getMainLooper());
        handlerThree.post(new Runnable(){
            public void run(){
                Toast.makeText(MyApplication.getContext(),text,Toast.LENGTH_LONG).show();
            }
        });
    }
}
